package com.springboot.seckill.controller;

import com.springboot.seckill.controller.dto.CreateOrderDTO;
import com.springboot.seckill.error.BusinessException;
import com.springboot.seckill.error.EmBusinessError;
import com.springboot.seckill.response.CommonReturnType;
import com.springboot.seckill.service.OrderService;
import com.springboot.seckill.service.model.OrderModel;
import com.springboot.seckill.service.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: HuangDekai
 * @Date: 2022/3/26 15:19
 * @Version: 1.0
 * @since: jdk11
 */
@RestController("order")
@RequestMapping("/order")
//DEFAULT_ALLOWED_HEADERS: 允许跨域传输所有的header参数, 将用于使用token放入header域, 做session共享的跨域请求
//DEFAULT_ALLOW_CREDENTIALS = true: 需要配合前端设置xhrFields授信后使得跨域session共享
@CrossOrigin(allowCredentials = "true",  allowedHeaders = "*", originPatterns = "*")
public class OrderController extends BaseController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @PostMapping(value="/create", consumes= MediaType.APPLICATION_JSON_VALUE)
    public CommonReturnType createOrder(@RequestBody CreateOrderDTO createOrderDTO) throws BusinessException {
        Boolean isLogin = (Boolean) httpServletRequest.getSession().getAttribute("IS_LOGIN");
        if (isLogin == null || !isLogin) {
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN, "用户未登录,不能下单");
        }
        UserModel userModel = (UserModel) httpServletRequest.getSession().getAttribute("LOGIN_USER");
        OrderModel orderModel = orderService.createOrder(userModel.getId(), createOrderDTO.getItemId(), createOrderDTO.getPromoId(), createOrderDTO.getAmount());

        return CommonReturnType.create(null);
    }
}
